package com;


import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.*;


import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;


public class Votepost extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6296714409545506786L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		if(req.getParameter("blob-key")!=null){
			BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
			BlobKey blobKey = new BlobKey(req.getParameter("blob-key"));
			blobstoreService.serve(blobKey, resp);
		}
		
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
        resp.setContentType("text/plain");
		
		String topic = req.getParameter("topic");
		String uid = req.getParameter("uid");
		long limit = 86400000; // one day
        Date date = new Date();
        Entity post = new Entity("Post");
        post.setProperty("uid", hash(uid));
        post.setProperty("topic", topic);
        post.setProperty("date", date);
        post.setProperty("timelimit", limit);
        post.setProperty("yes", 0);
        post.setProperty("no", 0);
        post.setProperty("valid","1");
        
        
        BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
		
		BlobKey blobKey1= blobs.get("upimg1").get(0);
		BlobKey blobKey2= blobs.get("upimg2").get(0);
		BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey1);
		long key1size = blobInfo.getSize();
		blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey2);
		long key2size = blobInfo.getSize();
		String k1 = blobKey1.getKeyString();
		String k2 = blobKey2.getKeyString();
		
		if(key1size == 0) {
			blobstoreService.delete(blobKey1);
			k1="null";
		}
		if(key2size == 0) {
			blobstoreService.delete(blobKey2);
			k2="null";
		}
		
		post.setProperty("img1",k1);
		post.setProperty("img2",k2);
		
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(post);
			
		//resp.sendRedirect("/nose.jsp?blob-key="+blobKey1.getKeyString());
		
        resp.sendRedirect("/");
        
        //resp.getWriter().write("topic: "+topic+"\n"+"uid: "+uid+"\n"+"date: "+date+"\n"+"img1: "+key1size+"\n"+"img2: "+key2size+"\n");
	
		
	}


	public String hash(String i){
		String digest = "null";
		try{
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(i.getBytes());
		byte[] md5sum = md.digest();
		BigInteger bigInt = new BigInteger(1, md5sum);
		digest = bigInt.toString(16);
		while ( digest.length() < 32 ) {
		    digest = "0"+digest;
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return digest;
	}
}




/*
ServletFileUpload upload = new ServletFileUpload();
try{
	FileItemIterator iter = upload.getItemIterator(req);
	while(iter.hasNext()){
		FileItemStream item = iter.next();
        InputStream stream = item.openStream();

        resp.setContentType("text/plain");
        if (item.isFormField()) {
          resp.getWriter().write("Got a form field: " + item.getFieldName()+"\n");
        } else {
          resp.getWriter().write("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()+"\n");
          
          if(item.getName()!=null){
        	  int len;
        	  byte[] buffer = new byte[8192];
        	  while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
        		  resp.getWriter().write(new String(buffer).toCharArray(), 0, len/2);
        	  }
          }
          
        }
	}
}catch (Exception ex) {
	
    resp.setContentType("text/plain");
	resp.getWriter().write("My Error: "+ex.getMessage()+" ismulti: "+ upload.isMultipartContent(req));
}
*/